#include "include/storage.h"
#include "include/ltgsql.h"
#include <sys/stat.h>

struct ltgsql_storage_engine {
    char* data_dir;
    size_t page_size;
    size_t buffer_pool_size;
    ltgsql_bool use_wal;
    ltgsql_bool use_compression;
    // 更多状态信息...
};

ltgsql_storage_engine_t* ltgsql_storage_create(const ltgsql_storage_config* config) {
    ltgsql_assert(config != NULL);

    ltgsql_storage_engine_t* engine = ltgsql_malloc(sizeof(ltgsql_storage_engine_t));
    if (!engine) {
        return NULL;
    }

    engine->data_dir = ltgsql_strdup(config->data_dir);
    engine->page_size = config->page_size > 0 ? config->page_size : 8192;
    engine->buffer_pool_size = config->buffer_pool_size > 0 ? config->buffer_pool_size : 1048576;
    engine->use_wal = config->use_wal;
    engine->use_compression = config->use_compression;

    // 创建数据目录
    struct stat st = {0};
    if (stat(config->data_dir, &st) == -1) {
        if (mkdir(config->data_dir, 0755) == -1) {
            ltgsql_log(LTGSQL_LOG_ERROR, "Failed to create data directory: %s", config->data_dir);
            ltgsql_free(engine->data_dir);
            ltgsql_free(engine);
            return NULL;
        }
    }

    ltgsql_log(LTGSQL_LOG_INFO, "Storage engine created at: %s", config->data_dir);
    ltgsql_log(LTGSQL_LOG_INFO, "Page size: %zu, Buffer pool: %zu",
               engine->page_size, engine->buffer_pool_size);

    return engine;
}

void ltgsql_storage_destroy(ltgsql_storage_engine_t* engine) {
    if (engine) {
        ltgsql_free(engine->data_dir);
        ltgsql_free(engine);
        ltgsql_log(LTGSQL_LOG_INFO, "Storage engine destroyed");
    }
}

ltgsql_status ltgsql_storage_create_table(ltgsql_storage_engine_t* engine,
                                        const ltgsql_table_metadata* meta) {
    ltgsql_assert(engine && meta);

    char table_path[512];
    snprintf(table_path, sizeof(table_path), "%s/%s.ltg", engine->data_dir, meta->name);

    FILE* fp = fopen(table_path, "w");
    if (!fp) {
        ltgsql_log(LTGSQL_LOG_ERROR, "Failed to create table file: %s", table_path);
        return LTGSQL_IO_ERROR;
    }

    // 写入表元数据头
    // TODO: 实现完整的元数据序列化

    fclose(fp);
    ltgsql_log(LTGSQL_LOG_INFO, "Table created: %s", meta->name);

    return LTGSQL_OK;
}